<template>
 <div id="example" style="padding:50px;">
   <p>原始数据：{{message}}</p>
   <p>计算属性处理后数据：{{reversedMessage}}</p>
   <hr>
   <div>{{ fullName }}</div>
   <hr>
   <p>
      Ask a yes/no question:
    <input v-model="question">
   </p>
   <p>{{answer}}</p>
   <hr>
   <h4>动态切换class</h4>
   <el-button size="small" type="success" @click="changeColor">点我变色</el-button>
   <div v-bind:class="{active:isActive,'text-danager':hasError}"></div>。
   <!-- 绑定的数据不必在内联里 -->
   <div v-bind:class="classObject"></div>。
   <!-- 也可以绑定一个返回对象的计算属性 -->
   <div v-bind:class="classComputed"></div>
</div>
</template>

<script>
export default {
  name:'test',
  data(){
   return{
    message:'wangyaru1111',
    firstName: 'Foo',
    lastName: 'Bar',
    question:'',
    answer:'I cannot give you an answer until you ask a question!',
    isActive:true,
    error:null,
    hasError:false,
    classObject:{
      active:true,
      'text-danger':false
    }
   }
  },
  wathch:{
   /* 如果question发生改变，这个函数就会执行 */
    question: function (newQuestion, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  /* 计算属性不用在data中声名了直接使用数据 */
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    },
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    },
    /* 动态绑定样式的计算属性  */
    classComputed(){
      return{
        active:this.isActive&&!this.error,
        'text-danger':this.error&&this.error.type==='fatal'
      }
    }
  },
  created(){
      // this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods:{
    getAnswer(){
      if (this.question.indexOf('?')===-1) {
         this.answer='Questions usually contain a question mark'
         return
      }
      this.answer='Thinking......'
      var vm=this
      axios.get('http://yesno.wtf/api')
      .then(res=>{
        vm.answer=_.capitalize(response.data.answer)
      })
      .catch(err=>{
       vm.answer='Error! Could not reach the API.'
      })
    },
    /* 动态绑定class,点击按钮变色 */
    changeColor(){
      this.isActive=false
      this.hasError=true
      // this.isActive!==this.hasError
    }
  }
}
</script>

<style scoped>
.active {
  width: 100px;
  height: 100px;
  background-color: red;
}
.text-danager {
  width: 200px;
  height: 200px;
  background-color: pink;
}
</style>
